package com.wzh.yebServe.config.security;

import com.wzh.yebServe.pojo.Menu;
import com.wzh.yebServe.pojo.Role;
import com.wzh.yebServe.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 权限控制
 * 因为通过url可以直接访问到权限不足的路由，因此可以通过该过滤器解决此问题
 * @Author wzh
 * @create 2022/11/13 16:11
 * @Description: 根据请求url分析请求所需要的角色
 */
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private IMenuService menuService;

    //Ant 样式路径模式的实现。
    AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

        //获取请求的url
        String requestUrl = ((FilterInvocation) object).getRequestUrl ();
        //查询出来了每一个菜单及其对应所需要的角色
        List<Menu> menus = menuService.getMenusWithRole ();
        //遍历资源，查找用户访问的资源
        for (Menu menu : menus) {
            //判断请求的url与角色是否匹配
            if (antPathMatcher.match (menu.getUrl (),requestUrl)){
                String[] str = menu.getRoles ().stream ().map (Role::getName).toArray (String[]::new);
                //把匹配上的角色放入list
                return SecurityConfig.createList (str);
            }
        }
        //没匹配的url默认登录即可访问
        return SecurityConfig.createList ("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
